/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package ui;

import bus.AccountBUS;
import bus.ContactBUS;
import bus.MessageBUS;
import dao.MSAccessProvider;
import dto.AccountDTO;
import dto.ContactDTO;
import dto.MessageDTO;
import excom.JBoxEvent;
import excom.JBoxEventListener;
import excom.JContactBox;
import excom.JMailBox;
import excom.JOutlookBar;
import excom.OutlookContact;
import excom.OutlookMail;
import excom.OutlookMail.MailMode;
import excom.StatusBar;
import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.LayoutManager;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.io.File;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import utils.*;
import org.jvnet.flamingo.ribbon.*;
import outlook.Mailer;

/**
 * Main form
 * @author chanhpm
 */
public class MainForm extends JRibbonFrame implements ActionListener{

    public final String OutLookTitle = "JOutLook";
    public String currentBarName = "Mail";
    public static String ResourceDir = System.getProperty("user.dir") + "\\src\\ui\\resources\\";
    
    public MainForm(){
        super();

        if(new File(System.getProperty("user.dir") + "\\Outlook.mdb").exists()) {
            MSAccessProvider.setFullDbPath(System.getProperty("user.dir") + "\\Outlook.mdb");
        } else if(new File(System.getProperty("user.dir") + "\\dist\\Outlook.mdb").exists()){
            MSAccessProvider.setFullDbPath(System.getProperty("user.dir") + "\\dist\\Outlook.mdb");
        } else {
            MSAccessProvider.setFullDbPath(System.getProperty("user.dir") + "\\src\\resources\\Outlook.mdb");
        }
        
        initOutlookComponents();
    }
    
    //<editor-fold defaultstate="collapsed" desc="Initialize Menubar">
    private JMenuBar outlookMenuBar;
    private JMenu fileMenu;
    //private JMenu editMenu;
    private JMenu viewMenu;
    //private JMenu goMenu;
    private JMenu toolMenu;
    //private JMenu actionMenu;
    private JMenu helpMenu;
    private JMenu themeMenu;

   

    private void initMenuBar(){
        outlookMenuBar = new  JMenuBar();

        fileMenu = new JMenu("File");
        fileMenu.setMnemonic(KeyEvent.VK_F);
        fileMenu.add(createMenuItem("Exit", "Exit",
                KeyStroke.getKeyStroke(KeyEvent.VK_F4, ActionEvent.ALT_MASK)));

        viewMenu = new JMenu("View");
        viewMenu.add(createMenuItem("Switch", "Switch",
                KeyStroke.getKeyStroke(KeyEvent.VK_F2, ActionEvent.ALT_MASK)));
        viewMenu.setMnemonic(KeyEvent.VK_V);

        toolMenu = new JMenu("Tools");
        toolMenu.setMnemonic(KeyEvent.VK_T);
        toolMenu.add(createMenuItem("Account Settings", "acc_settings"));

        helpMenu = new JMenu("Help");
        helpMenu.setMnemonic(KeyEvent.VK_H);

        themeMenu = new JMenu("Theme");
        String[] supportedLnf = ThemeManager.getSupportedLnFs();
        for(String lnfName : supportedLnf) {
            themeMenu.add(createMenuItem(lnfName, lnfName));
        }

        outlookMenuBar.add(fileMenu);
        outlookMenuBar.add(viewMenu);
        outlookMenuBar.add(toolMenu);
        outlookMenuBar.add(helpMenu);
        outlookMenuBar.add(themeMenu);
    }

    private JMenuItem createMenuItem(String text,String commandText, KeyStroke stroke) {
        JMenuItem item = new JMenuItem(text);
        item.setActionCommand(commandText);
        item.setAccelerator(stroke);
        item.addActionListener(this);
        return item;
    }

    private JMenuItem createMenuItem(String text,String commandText) {
        JMenuItem item = new JMenuItem(text);
        item.setActionCommand(commandText);
        item.addActionListener(this);
        return item;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Initialize Toolbar">
    
    private JToolBar outlookToolBar;
    private JButton btnNew;    
    private JButton btnSendAndReceive;

    private void initToolBar(){
        outlookToolBar = new JToolBar("outlookToolBar");
        outlookToolBar.setFloatable(false);
        outlookToolBar.setRollover(true);
        outlookToolBar.setBorderPainted(false);
        
        btnNew= createOutlookToolBarButton("New",new ImageIcon(ResourceDir + "NewMessage.png"));
        btnNew.setActionCommand("ComposeMail");
        btnNew.addActionListener(this);
       
        btnSendAndReceive = createOutlookToolBarButton("Get mail");
        btnSendAndReceive.setActionCommand("receivedmail");
        btnSendAndReceive.addActionListener(this);
        outlookToolBar.add(btnNew);        
        outlookToolBar.add(btnSendAndReceive);
    }
    private JButton createOutlookToolBarButton(String name, Icon icon){
        JButton btn = new JButton(name, icon);
        btn.setBorderPainted(false);
        btn.setFocusPainted(false);
        return btn;
    }
    private JButton createOutlookToolBarButton(String name){
        JButton btn = new JButton(name);
        btn.setBorderPainted(false);
        btn.setFocusPainted(false);
        return btn;
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Layout Content">
    private JPanel createOutlookHeader(){
        JPanel header = new JPanel(new BorderLayout());
        initMenuBar();
        initToolBar();
        header.add(outlookMenuBar, BorderLayout.NORTH);
        header.add(outlookToolBar, BorderLayout.SOUTH);
        //initRibbon();
        //header.add(myRibbon, BorderLayout.SOUTH);
        return header;
    }

    private JOutlookBar outlookBar;
    private JMailBox mailbox;
    private OutlookMail outlookMail;
    private OutlookContact outlookContact;
    private JContactBox contactbox;

    /**
     * phan ben trai cua outlook
     * @return
     */
    private JPanel createOutlookBodyLeft()
    {
        JPanel panel = new JPanel(new BorderLayout());
        outlookBar = new JOutlookBar();      
        mailbox = new JMailBox();
        contactbox = new JContactBox();        
        outlookBar.addBar("Mail", mailbox);
        outlookBar.addBar("Contact",contactbox);
        outlookBar.setVisibleBar(0);
        outlookBar.addJBoxListener(new JBoxEventListener() {

            public void myJBoxEvent(JBoxEvent evt) {
                //throw new UnsupportedOperationException("Not supported yet.");
                JOutLookBarTrigger(evt);
            }
        });
        
        panel.add(outlookBar);

        mailbox.addJBoxListener(new JBoxEventListener() {

            public void myJBoxEvent(JBoxEvent evt) {
                JBoxEventTrigger(evt);
            }
        });
        contactbox.addJBoxListener(new JBoxEventListener() {

            public void myJBoxEvent(JBoxEvent evt) {
                JBoxEventTrigger(evt);
            }
        });
        
        return panel;
    }

    /**
     * phan ben phai cua outlook
     * @return
     */
    private JPanel createOutlookBodyRight()
    {
        JPanel panel = new JPanel(new BorderLayout());
        outlookMail = new OutlookMail(OutlookMail.MailMode.Inbox);
        outlookContact = new OutlookContact();
        panel.add(outlookMail, BorderLayout.CENTER);
        //panel.add(outlookContact, BorderLayout.CENTER);
       // outlookContact.setVisible(false);
        return panel;
    }
    private JSplitPane mainSplitPane;
    private JPanel outlookBodyLeft;
    private JPanel outlookBodyRight;
    
    
    private JPanel createOutlookBody(){
        JPanel body = new JPanel(new BorderLayout());
        outlookBodyLeft = createOutlookBodyLeft();
        outlookBodyRight = createOutlookBodyRight();
        mainSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, outlookBodyLeft,outlookBodyRight);
        mainSplitPane.setResizeWeight(0.1);
        mainSplitPane.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));
        mainSplitPane.setName("mainSplitPane");
        mainSplitPane.setOpaque(true);
        mainSplitPane.setDividerSize(5); 
        mainSplitPane.setEnabled(true);
        body.add(mainSplitPane,BorderLayout.CENTER);
        return body;
    }


    private JPanel createOutlookFooter(){
        JPanel footer = new JPanel(new BorderLayout());
        return footer;

    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Initialize Components">
    private LayoutManager oulookLayout;
    private JPanel outlookHeader;
    private JPanel outlookFooter;
    private JPanel outlookBody;
    private StatusBar statusBar;

    private void initOutlookComponents(){

       Container container = this.getContentPane();
       oulookLayout = new BorderLayout();
       container.setLayout(oulookLayout);

       outlookHeader = createOutlookHeader();
       outlookBody = createOutlookBody();
       outlookFooter = createOutlookFooter();
       statusBar = new StatusBar();

       container.add(outlookHeader,BorderLayout.NORTH);
       container.add(outlookBody, BorderLayout.CENTER);
       container.add(outlookFooter, BorderLayout.SOUTH);
       container.add(statusBar, BorderLayout.SOUTH);
       
       setTitle(OutLookTitle);
    }
    //</editor-fold>

    //<editor-fold defaultstate="collapsed" desc="Handle events">

    public void actionPerformed(ActionEvent e) {
        //throw new UnsupportedOperationException("Not supported yet.");
        String command = e.getActionCommand();

        if(command.equals("ComposeMail")){
            composeMail();
        }
        else if(command.equalsIgnoreCase("receivedmail")) {
            getMail();
            getMail();
        }
        else if (command.equals("Switch")){
            outlookMail.changeViewState();
        }
        else if(command.equals("acc_settings")) {
            AccountSettingsPanel panel = new AccountSettingsPanel();
            panel.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            panel.show();
        }
        else if (command.equals("Exit")){
            this.dispose();
        }
        else {
            try {
                // themes
                ThemeManager.changeLookAndFeel(command, this);
            } catch (Exception ex) {
                Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    /*
     * soan mail
     */
    private void composeMail() {
       MailComposePanel frm = new MailComposePanel();
       frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
       frm.setVisible(true);
       frm.addJBoxListener(new JBoxEventListener() {

            public void myJBoxEvent(JBoxEvent evt) {
               //JOptionPane.showConfirmDialog(null,"aaaaaaaa","abc",JOptionPane.PLAIN_MESSAGE);
                if(evt.get_name().equalsIgnoreCase("sendmessage")){
                    MsgboxHelper.inform("Message sent");
                    outlookMail.refresh();
                }
                else
                {
                    MsgboxHelper.inform("Message saved");
                    outlookMail.refresh();
                }
                repaint();
                validate();
            }
        });
    }

    
    public void JBoxEventTrigger(JBoxEvent evt){
        outlookBodyRight.removeAll();

        if(evt.get_name().equalsIgnoreCase("Inbox")){
            outlookBodyRight.add(outlookMail,BorderLayout.CENTER);
            outlookMail.switchMode(MailMode.Inbox);
            outlookMail.refresh();
        }
        else if(evt.get_name().equalsIgnoreCase("Outbox")){
            outlookBodyRight.add(outlookMail,BorderLayout.CENTER);
            outlookMail.switchMode(MailMode.OutBox);
            outlookMail.refresh();
        }
        else if (evt.get_name().equalsIgnoreCase("Drafts"))
        {
           outlookBodyRight.add(outlookMail,BorderLayout.CENTER);
           outlookMail.switchMode(MailMode.Draft);
           outlookMail.refresh();
        }
        else if(evt.get_name().equalsIgnoreCase("New"))// add new contact
        {// addnewcontact

            outlookBodyRight.add(outlookContact,BorderLayout.CENTER);
            outlookContact.inquire();
            ContactAddPanel frm = new ContactAddPanel(-1);
            frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            frm.setVisible(true);
            frm.addJBoxListener(new JBoxEventListener() {

                public void myJBoxEvent(JBoxEvent evt) {
                   // JOptionPane.showConfirmDialog(null,"aaaaaaaa","abc",JOptionPane.PLAIN_MESSAGE);
                    outlookContact.refresh();
                }
            });            
        }
        else if(evt.get_name().equalsIgnoreCase("update"))// update contact
        {
            outlookBodyRight.add(outlookContact,BorderLayout.CENTER);
            outlookContact.inquire();
            int i = outlookContact.getContactIDSelected();
            //JOptionPane.showConfirmDialog(null,i,"abc",JOptionPane.PLAIN_MESSAGE);
            if (i >= 0){
                ContactAddPanel frm = new ContactAddPanel(i);
                frm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
                frm.setVisible(true);
                frm.addJBoxListener(new JBoxEventListener() {

                    public void myJBoxEvent(JBoxEvent evt) {
                        //JOptionPane.showConfirmDialog(null,"aaaaaaaa","abc",JOptionPane.PLAIN_MESSAGE);
                        outlookContact.refresh();
                    }
                });
            }
        }
         else if(evt.get_name().equalsIgnoreCase("delete"))// delete contact
        {
            outlookBodyRight.add(outlookContact,BorderLayout.CENTER);
            outlookContact.inquire();
            int i = outlookContact.getContactIDSelected();
            //JOptionPane.showConfirmDialog(null,i,"abc",JOptionPane.PLAIN_MESSAGE);
            if (i >= 0){
                ContactDTO dto;
                try {
                    dto = new ContactBUS().getInfo(i);
                    if(dto != null)
                    {
                        // confirm delete
                        if(MsgboxHelper.confirm("Do you really want to delete this contact?"))
                        {                   
                            new ContactBUS().deleteContact(dto);
                            MsgboxHelper.inform("Contact deleted");
                            outlookContact.refresh();
                            //validate();
                        }
                    }
                } catch (SQLException ex) {
                    Logger.getLogger(MainForm.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
        else if(evt.get_name().equalsIgnoreCase("search"))
        {
            outlookBodyRight.add(outlookContact,BorderLayout.CENTER);
            outlookContact.inquire();
            ContactSearchPanel searchfrm = new ContactSearchPanel();
            searchfrm.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
            searchfrm.setVisible(true);
        }
        else if(evt.get_name().equalsIgnoreCase("del message"))
        {
            outlookBodyRight.add(outlookMail,BorderLayout.CENTER);
            MessageDTO dto = outlookMail.getMsgSelected();
            new MessageBUS().deleteMessage(dto);
            MsgboxHelper.inform("Message deleted");
            outlookMail.refresh();

        }
        repaint();
        validate();
    }

    public void JOutLookBarTrigger(JBoxEvent evt){
        outlookBodyRight.removeAll();
        currentBarName = evt.get_name();
        if(currentBarName.equalsIgnoreCase("Mail"))
        {
            outlookBodyRight.add(outlookMail,BorderLayout.CENTER);
            outlookMail.switchMode(MailMode.Inbox);
        }
        else if (currentBarName.equalsIgnoreCase("Contact")){
             outlookBodyRight.add(outlookContact,BorderLayout.CENTER);
             outlookContact.inquire();
        }
        repaint();
        validate();
        //JOptionPane.showConfirmDialog(null,evt.get_name(),"abc",JOptionPane.PLAIN_MESSAGE);
    }

    private void getMail(){
        AccountDTO ca = new AccountBUS().getAllRecords().get(0);
        
        ArrayList<MessageDTO> rm= Mailer.getMail(ca) ;
        for(int i = 0; i < rm.size(); i++) {
            rm.get(i).setType("Inbox");
            new MessageBUS().insertMessage(rm.get(i));
        }

        outlookMail.switchMode(MailMode.Inbox);
        outlookMail.refresh();
    }
    //</editor-fold>
}
